package cms.com.yh.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 功能:
 * Author: yuhui
 * Date: 2021/4/9 8:58
 */
public class loginFilter implements Filter {
    String[] nofilter;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String cango = filterConfig.getInitParameter("cango");
        nofilter = cango.split(",");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse)servletResponse;

        String uri = req.getRequestURI();
        System.out.println(uri);
        if(uri.endsWith(nofilter[0])){
            filterChain.doFilter(servletRequest,servletResponse);
        }else if(uri.endsWith(nofilter[1])){
            if(req.getParameter("card") == null){
                if(req.getSession().getAttribute("user") != null){
                    req.getRequestDispatcher("/WEB-INF/view/main.jsp").forward(req,resp);
                }else{
                    resp.sendRedirect("/index.jsp");
                }
            }
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            Object user = req.getSession().getAttribute("user");
            if(user != null && uri.endsWith(".do")){
                filterChain.doFilter(servletRequest,servletResponse);
            }else{
                req.getRequestDispatcher("/index.jsp").forward(req,resp);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
